using System;
using NHibernate;
using NUnit.Framework;
using Sample.Domain;
using Sample.Persistence;
using Sample.Service;

namespace SampleTests
{
    [TestFixture]
    public class When_using_transactions
    {
        #region Setup/Teardown

        [SetUp]
        public void ResetDb()
        {
            NHibernateHelper.GenerateSchema(false);
        }

        #endregion

        [Test]
        public void Throwing_an_exception_prevents_anything_from_being_saved()
        {
            Assert.Throws<Exception>(() =>
                                         {
                                             using (ISession session = NHibernateHelper.OpenSession())
                                             {
                                                 Person person = ObjectMother.ValidPerson();
                                                 Person person2 = ObjectMother.ValidPersonTwo();

                                                 using (ITransaction transaction = session.BeginTransaction())
                                                 {
                                                     var ps = new PersonService(session);
                                                     ps.SaveChanges(person);
                                                     ps.SaveChanges(person2);
                                                     throw new Exception();
                                                     transaction.Commit();
                                                 }
                                             }
                                         });

            using (ISession session = NHibernateHelper.OpenSession())
            {
                var ps = new PersonService(session);
                long count = ps.Count();
                Assert.AreEqual(0, count);
            }
        }
    }
}